// routes/wechat.js

const Joi = require("joi");
const config = require("../config");
const _request = require("../utils/request");

const GROUP_NAME = "wechat";

module.exports = [
  {
    method: "POST",
    path: `/${GROUP_NAME}/login`,
    handler: async (request, reply) => {
      let result = await _request.get(`https://api.weixin.qq.com/sns/jscode2session`,{
        appId: config.appId,
        appSecret: config.appSecret,
        js_code: request.payload.code,
        grant_type: 'authorization_code',
      });
      if (result.data) {
        if (!!result.data.errcode && !!result.data.errmsg) {
          reply({
            errorCode: -1,
            errorMessage: result.data.errmsg
          });
        } else {
          reply({
            errorCode: 0,
            errorMessage: "success",
            result: result.data
          });
        }
      }
    },
    config: {
      tags: ["api", GROUP_NAME],
      description: "用户登录，微信小程序专用",
      auth: false, // 约定此接口不参与 JWT 的用户验证，会结合下面的 hapi-auth-jwt 来使用
      validate: {
        payload: {
          code: Joi.string().required()
        }
      }
    }
  }
];
